# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from urllib.parse import urlencode
import requests
from threading import Thread
from common.helper import Helper

class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "健康保重大疾病保险"

    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 41)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "200000", "300000", "400000", "500000"],
                # 保障期限
                "expire": ["70岁", "80岁", "终身"],
                # 交费期间
                "interval": ["0", "5", "10", "15", "20", "30"],
                # 轻疾包赔
                "slightDisease": ["0", "1"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(41, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "200000", "300000", "400000", "500000"],
                # 保障期限
                "expire": ["70岁", "80岁", "终身"],
                # 交费期间
                "interval": ["0", "5", "10", "15"],
                # 轻疾包赔
                "slightDisease": ["0", "1"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(46, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "200000", "300000"],
                # 保障期限
                "expire": ["70岁", "80岁", "终身"],
                # 交费期间
                "interval": ["0", "5", "10", "15"],
                # 轻疾包赔
                "slightDisease": ["0", "1"]
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(51, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "200000", "300000"],
                # 保障期限
                "expire": ["70岁", "80岁", "终身"],
                # 交费期间
                "interval": ["0", "5"],
                # 轻疾包赔
                "slightDisease": ["0", "1"]
            },
            "planE": {
                # 年龄段
                "year": [str(i) for i in range(56, 61)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "200000", "300000"],
                # 保障期限
                "expire": ["70岁", "80岁", "终身"],
                # 交费期间
                "interval": ["0", "5"],
                # 轻疾包赔
                "slightDisease": ["0", "1"]
            },
        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["money"], plan[k]["expire"],
                             plan[k]["interval"], plan[k]["slightDisease"]):
                data = Helper.formatProductInfo(plan[k], v)
                data["slightDisease"] = data["money"] if data["slightDisease"] != "0" else "0"
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None,mysql=None):
        birth = str(2020 - int(dt["year"]))
        sex = "0" if dt["gender"] == "M" else "1"
        if dt["slightDisease"] == "0":
            data = {
                'insuredsStr': '[{"birthday":"' + birth + '-01-01","sex":"' + sex + '","planInfos":[{"riskCode":"I138","mainRiskCode":"I138","planCode":"20","planPeriod":"' +
                               dt["expire"] + '","payType":"0","payEndYearFlag":"","payEndYear":' + dt[
                                   "interval"] + ',"dutys":[{"dutyCode":"138001","dutyAmnt":"'+dt["money"]+'"}]}]}]',
                'isOrder': '0',
                'productID': '26'
            }
        else:
            data = {
                'insuredsStr': '[{"birthday":"' + birth + '-01-01","sex":"' + sex + '","planInfos":[{"riskCode":"I138","mainRiskCode":"I138","planCode":"20","planPeriod":"' +
                               dt["expire"] + '","payType":"0","payEndYearFlag":"","payEndYear":' + dt[
                                   "interval"] + ',"dutys":[{"dutyCode":"138001","dutyAmnt":"' + dt[
                                   "money"] + '"}]},{"riskCode":"I139","mainRiskCode":"I138","planCode":"21","planPeriod":"' +
                               dt["expire"] + '","payType":"0","payEndYearFlag":"","payEndYear":' + dt[
                                   "interval"] + ',"dutys":[{"dutyCode":"139001","dutyAmnt":"' + dt[
                                   "money"] + '"}]}]}]',
                'isOrder': '0',
                'productID': '26'
            }


        payload = urlencode(data).replace("+", "")
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        try:
            if r.status_code == 200 and r.json()["data"]["data"]["insureds"][0]["insurerPrem"] != "null":
                price = Helper.decimalParse(r.json()["data"]["data"]["insureds"][0]["insurerPrem"])
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                print( data )
                mysql.updatePrice( data )
            else:
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "state":3
                }
                mysql.updateTask(data)
                print("\n/*更新产品价格信息失败：%d*/"%dt["id"])
        except:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask(data)
            print("\n/*更新产品价格信息失败：%d*/" % dt["id"])
    def startProcess(self):
        threads = []
        for i in range(5):
            mysql = MysqlClient()
            t = Thread(target=Helper.runProcess,args=(mysql,self.name,self.requestJson ))
            t.start()
            threads.append( t )
        for t in threads:
            t.join()


